<?php
declare(strict_types=1);

namespace Modules\Production\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Illuminate\Support\Facades\DB;
use Modules\Base\Repository\MaterialRepository;use Modules\Production\Models\ProductionOrder;
use Illuminate\Http\Request;
use Modules\Production\Models\ProductionOrderDetail;
use Modules\Production\Repository\ProductionOrderRepository;
use Modules\Production\Repository\ProductionOrderStockUserRepository;
use Modules\Production\Service\ProductionOrderService;


class ProductionOrderController extends Controller
{

    public function __construct(
        protected readonly ProductionOrder $model
    ){}

    /**
     * @param Request $request
     * @return mixed
     */
    public function index(): mixed
    {
        $list = $this->model->getList();
        $list = $list->toArray();

        foreach ($list['data'] as &$value){
            $value['stock_user'] = ProductionOrderStockUserRepository::findByProductionId($value['id']);
        }
        return $list;

    }

    /**
     * 生产工单创建
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $orderData = $request->post();
        if(!isset($orderData['FEntry']) || count($orderData['FEntry']) < 1){
            throw new \Exception('单据体【FEntry】不能为空');
        }

        try {

            DB::beginTransaction();

            $hasProduction = ProductionOrderRepository::getIdByDocno($orderData['fbillno']);
            if($hasProduction){
                throw new \Exception("工单号[{$orderData['fbillno']}]已存在");
            }

            $material = MaterialRepository::findMaterial($orderData['fmaterialid']);
            if(!$material){
                throw new \Exception("品号[{$orderData['fmaterialid']}]不存在");
            }

            //单据头入库
            $orderId = $this->model->storeBy($request->all());

            //单据体入库
            foreach ($orderData['FEntry'] as &$items){

                $material = MaterialRepository::findMaterial($items['fmaterialid1']);
                if(!$material){
                    throw new \Exception("子项品号[{$items['fmaterialid1']}]不存在");
                }

                $items['production_order_id']   = $orderId;
                $items['creator_id']            = $this->getLoginUser()->id;
                $items['created_at']            = time();
            }
            (new ProductionOrderDetail())->insert($orderData['FEntry']);

            Db::commit();
            return [];
        }catch (\Exception $e){
            Db::rollBack();
            throw $e;
        }

    }

    /**
     * 生产工单明细查询
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        $order = $this->model->with(['details','stockUser','process'])->find($id);
        if(!$order){
            return [];
        }
        $order = $order->toArray();
        $order['production_qr_code'] = ProductionOrderRepository::makeProductionQrCode($order['fbillno']);

        foreach ($order['process'] as &$processVal){
            $processVal['qr_code'] = ProductionOrderRepository::makeFlowQrCode($order['fbillno'],$processVal['id']);
        }
        return $order;
    }

    /**
     * 生产工单修改
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update($id, Request $request)
    {
        return ProductionOrderRepository::update($id,$request->post());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        return $this->model->where('fid',$id)->delete();
    }

    /**
     * 工艺流程绑定
     * @param Request $request
     * @return mixed
     * @throws Exception
     */
    public function bindProcessFlow(Request $request){
        return ProductionOrderRepository::bindFlow($request->post());
    }

    /**
     * 生产汇报
     * @param Request $request
     */
    public function report(Request $request){
        return ProductionOrderService::productionReport($request->post());
    }
}
